package com.xywy.bloodandroid.util;


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;




/**
 * �ַ�Ĵ���
 * @author James mz
 *
 */
public class TextUtil {

	public static String getMD5Str(String str, String type) {
		MessageDigest messageDigest = null;

		try {
			messageDigest = MessageDigest.getInstance("MD5");
			messageDigest.reset();
			messageDigest.update(str.getBytes("UTF-8"));
		} catch (NoSuchAlgorithmException e) {
			System.exit(-1);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		byte[] byteArray = messageDigest.digest();

		StringBuffer md5StrBuff = new StringBuffer();

		for (int i = 0; i < byteArray.length; i++) {
			if (Integer.toHexString(0xFF & byteArray[i]).length() == 1)
				md5StrBuff.append("0").append(
						Integer.toHexString(0xFF & byteArray[i]));
			else
				md5StrBuff.append(Integer.toHexString(0xFF & byteArray[i]));
		}

		if (type.equals("16")) {
			// 16λ���ܣ��ӵ�9λ��25λ
			return md5StrBuff.substring(8, 24).toString().toUpperCase();
		} else {
			// 32λ����
			return md5StrBuff.toString().toUpperCase();
		}
	}

	/**
	 * 判断字符串是否为�?
	 * 
	 * @param str
	 * @return boolean
	 * @author: ccy Create at: 2012-4-13 上午11:17:56
	 */
	public static boolean chkStrEmpty(String str) {
		if (str.equals("") || str == null || str == "" || str.length() <= 0) {
			return true;
		}
		return false;
	}

	/**
	 * 判断email格式
	 * 
	 * @param str
	 * @return boolean
	 * @author: ccy Create at: 2012-4-13 上午11:30:52
	 */
	public static boolean isEmail(String str) {
		Pattern p = Pattern
				.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
		Matcher m = p.matcher(str);
		if (m.matches()) {
			return true;
		}
		return false;
	}
	
	/**
	 * 截取字符�?
	 *
	 * @param string
	 * @param length
	 * @return
	 * @author:     ccy
	 * Create at:   2012-5-23 下午3:36:45
	 */
	public static String subString(String string, int length) {
		if(string.length() > length) {
			string = string.substring(0, length);
		}
		return string;
	}
}
